import Datastore from 'nedb-promises'

/**
 * 更新
 * @param db
 * @param queryParams
 * @param newRecord
 * @param resJSON
 * @param callback
 */
const UpdateData = (db: Datastore<{ _id: string; }>, queryParams: any, newRecord: any, resJSON: ResponseDataType, callback: Function, multi?: boolean) => {
  // 查询是否存在
  db.find({ ...queryParams, _del: false }).then((res: any) => {
    let dataLen = res.length
    if (dataLen === 0) {
      resJSON.note = `id为 ${queryParams.id} 的记录不存在`
      callback && callback(resJSON)
    } else {
      // 更新
      db.update({ ...queryParams, _del: false }, { $set: newRecord }, { multi }).then(async (res: any) => {
        console.log('update', res)
        resJSON = {
          code: queryParams.id,
          note: '修改成功',
          data: [],
          total: res
        }
        callback && callback(resJSON)
      }).catch((error) => {
        resJSON.note = error
        callback && callback(resJSON)
      })
    }
  }).catch((error) => {
    resJSON.note = error
    callback && callback(resJSON)
  })
}

/**
 * 同步更新
 * @param db
 * @param queryParams
 * @param newRecord
 * @param resJSON
 * @returns
 */
const UpdateDataSync = async (db: Datastore<{ _id: string; }>, queryParams: any, newRecord: any, resJSON: ResponseDataType, multi?: boolean) => {
  // 查询是否存在
  await db.find({ ...queryParams, _del: false }).then(async (res: any) => {
    let dataLen = res.length
    if (dataLen === 0) {
      resJSON.note = `id为 ${queryParams.id} 的记录不存在`
    } else {
      // 更新
      await db.update({ ...queryParams, _del: false }, { $set: newRecord }, { multi }).then(async (res: any) => {
        console.log('update', res)
        resJSON = {
          code: queryParams.id,
          note: '修改成功',
          data: [],
          total: res
        }
      }).catch((error) => {
        resJSON.note = error
      })
    }
  }).catch((error) => {
    resJSON.note = error
  })
  return resJSON
}

export {
  UpdateData,
  UpdateDataSync,
}